package o2o.web.actions.shop;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.shop.ShopManagerRelationMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.shop.CLOUD_SHOP_APPLY_STATE;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.shop.ShopManagerRelation;
import o2o.dao.PO.sys.SysCustomerInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.service.shop.ShopService;
import o2o.web.actions.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

//店铺关联的业务员的关联（区域代理）
@Controller
public class ShopManagerController {


    //区域代理所管理的店铺列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/manager/relation/list")
    @ResponseBody
    public String shop_manager_list(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有管理权限");
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }

        return AjaxResult.successResult();
    }


    //添加店铺所属区域代理
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/manager/relation/add")
    @ResponseBody
    public String shop_manager_add(String token, String username, Long shopId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有管理权限");
        }
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺不能为空");
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺不存在，请查证");
        }
        UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userinfo) {
            return AjaxResult.errorResult("账号不存在，请查证");
        }
        if (0 == 1 - userinfo.getIsLock()) {
            return AjaxResult.errorResult("该账号已锁定，无法添加");
        }
        Boolean flag = addRelation(username, shopId, shopInfo.getOwnUsername(), user.getUsername());
        if (null != flag && flag) {
            return AjaxResult.successResult();
        } else {
            return AjaxResult.errorResult("添加失败，请稍后再试");
        }
    }

    //编辑店铺所属区域代理
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/manager/relation/modify")
    @ResponseBody
    public String shop_manager_modify(String token, String username, Long shopId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有管理权限");
        }
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺不能为空");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺不存在，请查证");
        }
        if (ValidateUtil.isNotNull(username)) {
            UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(username);
            if (null == userinfo) {
                return AjaxResult.errorResult("账号不存在，请查证");
            }
            if (0 == 1 - userinfo.getIsLock()) {
                return AjaxResult.errorResult("该账号已锁定，无法添加");
            }
        }

        Boolean flag = modifyShopRelation(username, shopId, shopInfo.getOwnUsername(), user.getUsername());
        if (null != flag && flag) {
            return AjaxResult.successResult();
        } else {
            return AjaxResult.errorResult("添加失败，请稍后再试");
        }
    }


    // 审核通过云商家
    @RequestMapping("/admin/cloud-shop/apply/state")
    @ResponseBody
    public String cloudApplyPassOrNo(String sysAppKey, String token, Long shopId, Integer cloudApplyState) {
        SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
        if (customerInfo == null) {
            return AjaxResult.errorResult("未查询到到当前的客户标识");
        }
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (cloudApplyState == null || (cloudApplyState != CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_NO_PASS && cloudApplyState != CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_PASS)) {
            return AjaxResult.errorResult("无效的操作请求");
        }
        try {
            ShopService.getInstance().passOrNoCloudShopApply(sysAppKey, shopId, cloudApplyState, user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        return AjaxResult.successResult();
    }

    //-----------------保存店铺所属的区域代理
    // 添加
    public static Boolean addRelation(String username, Long shopId, String shopUsername, String opUsername) {
        if (ValidateUtil.isNull(username) || ValidateUtil.isNotAbsLong(shopId)) {
            return false;
        }

        Long time = DateUtils.getCurrTime();
        ShopManagerRelation relation = new ShopManagerRelation();
        relation.setUsername(username);
        relation.setShopId(shopId);
        relation.setShopUsername(shopUsername);

        relation.setCreateUser(opUsername);
        relation.setCreateTime(time);

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SHOP_MANAGER_RELATION, relation);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        //更新缓存
        ShopManagerRelationMemory.getInstance().add(time);

        return true;
    }

    // 修改
    public static Boolean modifyShopRelation(String username, Long shopId, String shopUsername, String opUsername) {
        if (ValidateUtil.isNotID(shopId)) {
            return false;
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.SHOP_MANAGER_RELATION).append(" set delFlag =1 ,updateUser = '").append(opUsername)
                .append("' where delFlag = 0 and shopId =").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        ShopManagerRelationMemory.getInstance().delete(shopId);

        if (ValidateUtil.isNotNull(username)) {
            //添加新的关联
            return addRelation(username, shopId, shopUsername, opUsername);
        }
        return true;

    }

}
